package com.easyui.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.easyui.common.UserLogin;

public class ChangePswServlet extends HttpServlet {

	public ChangePswServlet() {}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		String role = request.getParameter("role");
		String userID = request.getParameter("userID");
		
		//JSONObject jsonAll = null;
		boolean success = false;
		String msg = "";
		
		if(role != null && userID != null) {
			String action = request.getParameter("action");
			if (action != null && action.equals("changePsw")) {
				String oldPsw = request.getParameter("oldPsw");
				String newPsw = request.getParameter("newPsw");
				String rePsw = request.getParameter("rePsw");
				
				UserLogin u = new UserLogin();
				if(u.checkTheSame(newPsw, rePsw)) {//newPsw和rePsw相同
					if(u.checkOldPsw(role, userID, oldPsw)) {//原密码正确
						if(u.setNewPsw(role, userID, newPsw)) {
							success = true;
						} else {
							System.out.println("设置新密码出错");
							success = false;
						}
					} else {
						System.out.println("原密码不正确");
						msg = "error_psw";
						success = false;
					}
				} else {
					System.out.println("新旧密码不一致");
					success = false;
				}
			} else {
				System.out.println("changePsw is wrong");
				success = false;
			}
		} else {
			System.out.println("role,userID is wrong");
			success = false;
		}
				
		if(success) {
			msg = "ok";
		} else {
			if(msg == null || msg.equals("")) {
				msg = "error";
			}
		}
		
		//jsonAll = new JSONObject();
		//jsonAll.put("success", success);
		//jsonAll.put("msg", msg);
		//out.print(jsonAll);
		
		out.write(msg);
		out.flush();
		out.close();
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		doPost(request, response);
	}
}
